package cn.group7.padserver.service.impl;

import cn.group7.padserver.entity.JwtUser;
import cn.group7.padserver.pojo.BankUser;
import cn.group7.padserver.pojo.User;
import cn.group7.padserver.service.BankUserService;
import cn.group7.padserver.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author 谷汉斌
 * @description 实现类实现UserDetasService接口，
 * 用于对 登录用户 进行验证以及权限获取 实现自定义登录验证
 * @createTime 2024/7/22 下午8:15
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private BankUserService bankUserService;

    /**
     * 根据用户名获取用户信息，实现自定义登录验证
     *
     * @param username 用户名
     * @return 封装的用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("验证用户名： {}", username);

        //从数据库获取用户信息
        User user = userService.selectByUserName(username);

        BankUser bankUser = bankUserService.selectByUserName(username);

        if (null == user && null == bankUser) {
            log.info("用户名： {} 不存在", username);
            throw new UsernameNotFoundException(String.format("%s.这个用户不存在", username));
        }
        if (null != user) {

            log.info("用户名： {} 存在", username);

            //获取用户角色，便于设置权限
            String role = user.getRole();
            //封装用户信息，并返回
            return new JwtUser(user.getUserName(), user.getNickName(), user.getPassword(), user.getAvatar(), AuthorityUtils.commaSeparatedStringToAuthorityList(role));
        }

        log.info("银行用户名： {} 存在", username);
        //获取用户角色，便于设置权限
        String role = bankUser.getRole();
        //封装用户信息，并返回
        return new JwtUser(bankUser.getUsername(), bankUser.getRealName(), bankUser.getPassword(), bankUser.getPhone(), AuthorityUtils.commaSeparatedStringToAuthorityList(role));

    }
}